package com.framework.boc.admin.pay.service;

import com.framework.boc.admin.constant.BOCUrlConstant;
import com.framework.boc.admin.pay.body.BocPayRequestBody;
import com.framework.boc.admin.pay.utils.BocPaySignTool;
import com.framework.boc.admin.pay.utils.DateTimeUtils;
import com.framework.boc.admin.properties.BocPayProperties;
import com.framework.boc.admin.utils.HttpClientUtil;
import com.framework.boc.error.CommonException;
import com.framework.boc.error.ErrorEnum;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

@Service
public class BocPayService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    BocPayProperties bocPayProperties;

    /**
     * 订单支付
     * @param bocPayRequestBody     支付参数
     */
    public String b2cRecvOrderWXAPP(BocPayRequestBody bocPayRequestBody) throws CommonException {

        String orderAmount = bocPayRequestBody.getOrderAmount();//订单金额
        String orderNote = bocPayRequestBody.getOrderNote();//订单说明
        String body = bocPayRequestBody.getBody();//商品描述
        String attach = bocPayRequestBody.getAttach();//附加数据

        // 下面为系统配置或默认参数
        String curCode = bocPayProperties.getPay().getCurCode();//订单币种
        String merchantNo = bocPayProperties.getPay().getMerchantNo();//商户号
        // 暂定商户号后六位加当前时间戳
        String orderNo =  merchantNo.substring(merchantNo.length() - 6) + LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")); //商户订单号 ，格式要求为：商户号（merchantNo）后6位+商户按自己规则生成的订单号；
        String payType = bocPayProperties.getPay().getPayType();//支付类型
        LocalDateTime orderTimeLocal = LocalDateTime.now();
        String orderTime = DateTimeUtils.formatTime(orderTimeLocal, "yyyyMMddHHmmss");//订单时间
        String orderUrl = bocPayProperties.getPay().getOrderUrl();//商户接收通知URL
        String orderTimeoutDate = "";//订单超时时间不传默认10分钟
        String terminalChnl = bocPayProperties.getPay().getTerminalChnl();//交易终端类型
        String mchtCustIP = "";//商户获取的客户IP地址
        String tradeType = bocPayProperties.getPay().getTradeType();//交易类型
        String deviceInfo = "wxh5";//设备号
        String spbillCreateIp = "127.0.0.1";//终端IP
        String limitPay = "";//指定支付方式
        String identityType = "";//证件类型
        String identityNumber = "";//证件号
        String identityName = "";//姓名

        //拼接原文
        StringBuffer sb = new StringBuffer();
        sb.append(orderNo).append("|")
                .append(orderTime).append("|")
                .append(curCode).append("|")
                .append(orderAmount).append("|")
                .append(merchantNo);
        if(null !=mchtCustIP && !"".equals(mchtCustIP) && mchtCustIP.trim().length()>0){
            sb.append("|").append(mchtCustIP);
        }
        String plainData = sb.toString();
        logger.info("原文="+plainData);
        String signData = null;
        try {
            signData = BocPaySignTool.sign(plainData, bocPayProperties.getPay().getPfxName(), bocPayProperties.getPay().getPfxPwd());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new CommonException(ErrorEnum.PARAMETER_ERROR, "加签失败");
        }
        //3、转BOC发送请求的参数
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("merchantNo", merchantNo));
        formParams.add(new BasicNameValuePair("payType", payType));
        formParams.add(new BasicNameValuePair("orderNo", orderNo));
        formParams.add(new BasicNameValuePair("curCode", curCode));
        formParams.add(new BasicNameValuePair("orderAmount", orderAmount));
        formParams.add(new BasicNameValuePair("orderTime", orderTime));
        formParams.add(new BasicNameValuePair("orderNote", orderNote));
        formParams.add(new BasicNameValuePair("orderUrl", orderUrl));
        formParams.add(new BasicNameValuePair("orderTimeoutDate", orderTimeoutDate));
        formParams.add(new BasicNameValuePair("terminalChnl", terminalChnl));
        formParams.add(new BasicNameValuePair("mchtCustIP", mchtCustIP));
        formParams.add(new BasicNameValuePair("signData", signData));
        formParams.add(new BasicNameValuePair("tradeType", tradeType));
        formParams.add(new BasicNameValuePair("deviceInfo", deviceInfo));
        formParams.add(new BasicNameValuePair("body", body));
        formParams.add(new BasicNameValuePair("attach", attach));
        formParams.add(new BasicNameValuePair("spbillCreateIp", spbillCreateIp));
        formParams.add(new BasicNameValuePair("limitPay", limitPay));
        formParams.add(new BasicNameValuePair("identityType", identityType));
        formParams.add(new BasicNameValuePair("identityNumber", identityNumber));
        formParams.add(new BasicNameValuePair("identityName", identityName));

        for (BasicNameValuePair basicNameValuePair : formParams) {
            logger.info(basicNameValuePair.getName()+"="+basicNameValuePair.getValue());
        }
        //4、发送请求
        String responseStr = HttpClientUtil.doPost(bocPayProperties.getPay().getBaseUrl() + BOCUrlConstant.B2CRECVORDER, formParams);
        return responseStr;

    }

}
